#include "matrix_operations.h"

void matrix_mul(Matrix a, Matrix b, Matrix result) {
    if (a.cols != b.rows) {
        fprintf(stderr, "Error: Number of columns in A must match number of rows in B.\n");
        return;
    }
    
    // 确保result矩阵已分配内存
    if (result.data == NULL) {
        result.data = (float*)malloc(a.rows * b.cols * sizeof(float));
        result.rows = a.rows;
        result.cols = b.cols;
    }

    // 初始化结果矩阵为0
    for (int i = 0; i < a.rows * b.cols; i++) {
        result.data[i] = 0.0f;
    }

    // 执行矩阵乘法 
    for (int i = 0; i < a.rows; i++) {
        for (int j = 0; j < b.cols; j++) {
            for (int k = 0; k < a.cols; k++) {
                result.data[i * b.cols + j] += a.data[i * a.cols + k] * b.data[k * b.cols + j];
            }
        }
    }
}

void print_matrix(Matrix m, int limit) {
    printf("Matrix Content (rows=%d, cols=%d):\n", m.rows, m.cols);
    int count = 0;
    
    for (int i = 0; i < m.rows && count < limit; i++) {
        for (int j = 0; j < m.cols && count < limit; j++) {
            printf("%.6f ", m.data[i * m.cols + j]);
            count++;
        }
        printf("\n");
    }
    
    if (m.rows * m.cols > limit) {
        printf("... (remaining elements omitted)\n");
    }
}

Matrix allocate_matrix(int rows, int cols) {
    Matrix m;
    m.rows = rows;
    m.cols = cols;
    m.data = (float*)malloc(rows * cols * sizeof(float));
    return m;
}

void free_matrix(Matrix m) {
    free(m.data);
}